package repository

import (
	"context"
	"database/sql"

	dbmodel "gitee.com/hp-huiw/family-expense-api/internal/db/model"
	jet "github.com/go-jet/jet/v2/mysql"
)

type AccountGroupRepository interface {
	Update(ctx context.Context, model *dbmodel.AccountGroup) error
	InsertWithTx(ctx context.Context, tx *sql.Tx, model *dbmodel.AccountGroup) error
	DeleteWithTx(ctx context.Context, tx *sql.Tx, accountGroupID string) error
}

// NewAccountGroupRepository creates a new AccountGroupRepository.
func NewAccountGroupRepository(db *sql.DB) AccountGroupRepository {
	return &accountGroupRepository{db}
}

func (r *accountGroupRepository) Update(ctx context.Context, model *dbmodel.AccountGroup) error {
	stmt := tbGroup.
		UPDATE(
			tbGroup.Title,
			tbGroup.LastUpdated,
		).
		MODEL(model).
		WHERE(
			tbGroup.ID.EQ(jet.String(model.ID)),
		)

	_, err := stmt.ExecContext(ctx, r.db)

	return err
}

// InsertWithTx inserts account group with transaction.
func (*accountGroupRepository) InsertWithTx(ctx context.Context, tx *sql.Tx, model *dbmodel.AccountGroup) error {
	stmt := tbGroup.
		INSERT().
		MODEL(model)

	_, err := stmt.ExecContext(ctx, tx)

	return err
}

// DeleteWithTx deletes account group by id with transaction.
func (*accountGroupRepository) DeleteWithTx(ctx context.Context, tx *sql.Tx, accountGroupID string) error {
	stmt := tbGroup.
		DELETE().
		WHERE(
			tbGroup.ID.EQ(jet.String(accountGroupID)),
		)

	_, err := stmt.ExecContext(ctx, tx)

	return err
}

type accountGroupRepository struct {
	db *sql.DB
}
